package com.yoooya.base.third.common;

import com.alibaba.fastjson.JSON;
import com.yoooya.base.dao.third.AccessTokenMapper;
import com.yoooya.base.model.po.third.AccessTokenPo;
import com.yoooya.base.utils.DateUtils;
import com.yoooya.base.utils.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @创建人 Sun Yijing
 * @创建时间 2018-07-08
 */
@Component
public class QzHelper {

	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Value("${qz.app.key}")
	private String appkey;
	@Value("${qz.app.seckey}")
	private String appSecret;
	private AccessToken accessToken;
	@Autowired
	private AccessTokenMapper tokenMapper;

	public String getAppKey() {
		return appkey;
	}

	public String getAppSecret() {
		return appSecret;
	}

	public String requestGet(String url) throws IOException {
		CloseableHttpClient client = HttpClientUtils.createSSLClientDefault();
		HttpGet get = new HttpGet(url);
		CloseableHttpResponse response = client.execute(get);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			return EntityUtils.toString(entity, StandardCharsets.UTF_8);
		}
		return null;
	}

	public String requestPost(String url, String outputStr) throws IOException {
		CloseableHttpClient client = HttpClientUtils.createSSLClientDefault();
		HttpPost post = new HttpPost(url);
		StringEntity stringEntity = new StringEntity(outputStr,
				StandardCharsets.UTF_8);
		post.setEntity(stringEntity);
		post.setHeader("Content-type", "application/json");
		CloseableHttpResponse response = client.execute(post);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			return EntityUtils.toString(entity, StandardCharsets.UTF_8);
		}
		return null;
	}

	public String getAccessToken() {
		String code = "qz";
		AccessTokenPo token = this.tokenMapper.queryByCode(code);
		if (null == token || token.isExpires()) {
			String url = "http://api.qianzhan.com/OpenPlatformService/GetToken?type=JSON&appkey="
					+ getAppKey() + "&seckey=" + getAppSecret();
			try {
				String access_token = requestGet(url);
				if (StringUtils.contains(access_token, "token")) {
					TokenResp resp = JSON.parseObject(access_token,
							TokenResp.class);
					if (resp.getStatus().equals("200")) {
						accessToken = resp.getResult();
						this.tokenMapper.updateToken(token.getId(),
								accessToken.getToken(),
								(int) accessToken.getExpiresIn(),
								DateUtils.getSecondTime(), new Date());
						token.setToken(accessToken.getToken());
					}

				} else {
					logger.error("获取token失败.[{}]", access_token);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
		return null == token ? null : token.getToken();
	}

	public void resetAccessToken() {
		String code = "qz";
		AccessTokenPo token = this.tokenMapper.queryByCode(code);
		String url = "http://api.qianzhan.com/OpenPlatformService/GetToken?type=JSON&appkey="
				+ getAppKey() + "&seckey=" + getAppSecret();
		try {
			String access_token = requestGet(url);
			if (StringUtils.contains(access_token, "token")) {
				TokenResp resp = JSON
						.parseObject(access_token, TokenResp.class);
				if (resp.getStatus().equals("200")) {
					accessToken = resp.getResult();
					this.tokenMapper.updateToken(token.getId(),
							accessToken.getToken(),
							(int) accessToken.getExpiresIn(),
							DateUtils.getSecondTime(), new Date());
				}
			} else {
				logger.error("获取token失败.[{}]", access_token);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	public static class TokenResp {
		private String status;

		private String message;

		private AccessToken result;

		public String getStatus() {
			return status;
		}

		public void setStatus(String status) {
			this.status = status;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}

		public AccessToken getResult() {
			return result;
		}

		public void setResult(AccessToken result) {
			this.result = result;
		}

	}

	public static class AccessToken {
		private String token;
		private int expiresIn = 720;
		private long time = DateUtils.getSecondTime();

		public boolean isExpires() {
			return DateUtils.getSecondTime() - time > expiresIn - 120;
		}

		public String getToken() {
			return token;
		}

		public void setToken(String token) {
			this.token = token;
		}

		public int getExpiresIn() {
			return expiresIn;
		}

		public void setExpiresIn(int expiresIn) {
			this.expiresIn = expiresIn;
		}
	}

}
